//
//  Configs.swift
//  FrameProduct
//
//  Created by delegate on 2024/2/3.
//

import Foundation
import DeviceKit
import Kingfisher
/// App相关的配置
public struct Configs {
    
    /// App 环境
    public enum Env: String, CaseIterable {
        case dev
        case test
        case prod
        case uat
    }
    
    
    public static let initialEnv = Env.uat
    public static var env: Env {
        return Env(rawValue: UserDefaults.standard.string(forKey: UserDefaultsKeys.appEnv) ?? "") ?? initialEnv
    }
    
    
    /// 常用UserDefaults 的key
    public struct UserDefaultsKeys {
        public static let appEnv = "appEnv"
//        public static let currentUser = "CurrentUserKey"
    }
    
    
    /// 常用keychain 的key
    public struct keychainKeys {
//        public static let userKey = "CurrentUserKey"
    }
    
    /// 域名api相关
    public struct BaseApi {
        /// 域名
        public static var url: URL {
            switch env {
            case .dev:
                return  URL(string: "https://www.baidu.com")!
            case .test:
                return URL(string: "https://www.baidu.com")!
            case .prod:
                return URL(string: "https://www.baidu.com")!
            case .uat:
                return URL(string: "https://www.baidu.com")!
            }
        }
        /// 请求头参数配置字典
        public static var deviceParameters: [String: String] = [
            "phoneModel": Device.current.model ?? "",
            "phoneName": Device.current.description,
            "systemType": Device.current.systemName ?? "",
            "systemVersion": Device.current.systemVersion ?? "",
            "uniIdentify": InstallUtil.uuid
        ]
        
        /// 请求头header
        public static var headers: [String: String] {
            var token = ""
            let tokenKey = "Authorization"
//            if let accessToken = AuthManager.shared.token?.token {
//                token = accessToken
//            }
            var dict = [tokenKey: token]
            dict.merge(deviceParameters)
            return dict
        }
    }
    
    
    /// App 协议相关url
    public enum ProtocolUrl {
        case user, service, logoff, appstore, register
        public var url : String{
            switch self {
            case .user:
                return ""
            case .service:
                return ""
            case .logoff:
                return ""
            case .register:
                return ""
            case .appstore:
                return ""
            }
        }
    }
    /// 一些sdk的key和app id
    public enum Keys {
        case aliyun, amap , tencentPush, netease, tencentBehavioralVerify,tencentFace, bugly
        
        public var apiKey: String {
            switch self {
            case .aliyun:
                return ""
            case .amap:
                return ""
            case .tencentPush:
                return ""
            case .netease:
                return ""
            case .tencentBehavioralVerify:
                return ""
            case .tencentFace:
                return ""
            case .bugly:
                return ""
            }
            
        }
        
        public var appId: String {
            switch self {
            case .aliyun:
                return ""
            case .amap:
                return ""
            case .tencentPush:
                return ""
            case .netease:
                return ""
            case .tencentBehavioralVerify:
                return ""
            case .tencentFace:
                return ""
            case .bugly:
                return ""
            }
        }
    }
    // 定义不同环境下一些h5页面的url
    public enum H5URL {
        case myCooperation
        public var url: URL {
            switch env {
            case .dev:
                return URL(string: "https://www.baidu.com")!
            case .test:
                return URL(string: "https://www.baidu.com")!
            case .prod:
                return URL(string: "https://www.baidu.com")!
            case .uat:
                return URL(string: "https://www.baidu.com/")!
            }
        }
    }
}


/// 缓存相关
public struct CacheConfigs {
    
    public static func clearAppCache() {
        ImageCache.default.clearMemoryCache()
        self.clearAppCache {}
    }
    
    public static func appCacheSize() -> String {
        return getAPPCacheSize()
    }
    
    ///清除缓存
    public static func clearAppCache(completion: @escaping () -> Void) {
        DispatchQueue.global().async {
            let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
            let fileArr = FileManager.default.subpaths(atPath: cachePath!)
            for file in fileArr! {
                let path = cachePath! + "/\(file)"
                if FileManager.default.fileExists(atPath: path) {
                    do {
                        try FileManager.default.removeItem(atPath: path)
                    } catch let err {
                        debugLog(err)
                    }
                }
            }
            DispatchQueue.main.async {
                completion()
            }
        }
    }
    /// 获取缓存
    public static func getAPPCacheSize() -> String {
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        var size = 0
        for file in fileArr! {
            let path = cachePath! + "/\(file)"
            let floder = try! FileManager.default.attributesOfItem(atPath: path)
            for (key, fileSize) in floder {
                if key == FileAttributeKey.size {
                    size += (fileSize as AnyObject).integerValue
                }
            }
        }
        let totalCache = Double(size) / 1024.00 / 1024.00
        ///为了满足产品需求展示0M
        if totalCache == 0.00 || totalCache == 0{
            return String(format: "0M")
        }else{
            return String(format: "%.2fM", totalCache)
        }
    }
}


extension Configs {
    public static func setupEnv() {
        self.setEnv(initialEnv)
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            UIViewController.initializeMethod()
        }
    }
    
    private static func setEnv(_ env: Env) {
        let oldValue = self.env
        if env == oldValue {
            return
        }
//        AuthManager.removeToken()
        UserDefaults.standard.set(env.rawValue, forKey: UserDefaultsKeys.appEnv)
        UserDefaults.standard.synchronize()
    }
    
    public static func changeEnvAlert() {
        let alert = Alert.with(title: "切换环境", message: "切换环境会清空你的登录信息\n当前环境:\(Configs.env.rawValue)，\nbaseURL{\(Configs.BaseApi.url.absoluteString)}", style: .alert)
        Configs.Env.allCases.forEach { env in
            alert.bind(button: env.rawValue, style: .default) { _ in
                if Configs.env == env {
                    return
                }
                Configs.setEnv(env)
                Toast.with(message: "已切换至:\(env.rawValue)环境，请重新登录")
                    .userInteractionEnabled(false)
                    .showOnWindow()
                DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                    UIViewController.initializeMethod()
                }
            }
        }
        alert.bind(button: "取消", style: .cancel)
            .show()
    }
}
